package epam.com.study.xml.classes;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import epam.com.study.xml.enums.StringToEnum;

public class LoadStones {
	
	private static final Logger log = Logger.getLogger(LoadStones.class);
	
	public static ListOfStones loadDOM(String fileName) {
		ListOfStones list = new ListOfStones();
		log.info("Begin parser DOM");
		try { 
		  File xmlFile = new File(fileName);
          DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
          Document document = documentBuilder.parse(xmlFile);
          document.getDocumentElement().normalize();
                  
          NodeList nodeList = document.getElementsByTagName("tns:stone");
          
          for (int i = 0; i < nodeList.getLength(); i++) {
        	  
        	  Stone stone = new Stone(); 
        	  Element currentElement = (Element) nodeList.item(i);
    		  stone.setId(Integer.parseInt(getNodeValue("tns:id", currentElement)) );
    		  stone.setName(getNodeValue("tns:name", currentElement));
    		  stone.setValue(Integer.parseInt(getNodeValue("tns:value", currentElement)) );
        	  String preciousness = getNodeValue("tns:preciousness", currentElement);
    		  stone.setPreciousness( StringToEnum.toTypeStone(preciousness) );
        	  
    		  VisualParameters visualParametrs = new VisualParameters();
    		  NodeList nodeListVisualParameters = currentElement.getElementsByTagName("tns:visual-parameters");
    		  currentElement = (Element)nodeListVisualParameters.item(0);
    		  visualParametrs.setEdge( Integer.parseInt(getNodeValue("tns:edge", currentElement)) );
    		  visualParametrs.setTransparency( Integer.parseInt(getNodeValue("tns:transparency", currentElement)) );
        	  String color = getNodeValue("tns:color", currentElement);
        	  visualParametrs.setColor( StringToEnum.toColor(color) );
        	  
        	  stone.visualParameters = visualParametrs;
        	  list.addStone(stone);    		
          }
		}
		catch (Exception e){
            log.error("Exception ", e);
        }
		log.info("End parser DOM");
		return list;
	}

    private static String getNodeValue(String childName, Element currentElement) {
        NodeList childList = currentElement.getElementsByTagName(childName);
        Element child = (Element) childList.item(0);
        Node node = child.getFirstChild();
        String value = node.getNodeValue();
        return value;
    } 	
	
}

